package com.android.love.web;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.webkit.MimeTypeMap;

import com.android.love.R;

import com.android.love.ui.DownloadsListActivity;
import com.android.love.util.LogUtil;

import java.io.File;
import java.util.Random;

/**
 * 下载任务
 */
public class DownloadItem {

	private Context mContext;

	private String mUrl;
	private String mFileName;

	private int mProgress;

	private String mErrorMessage;

	private DownloadRunnable mRunnable;

	private boolean mIsFinished;
	private boolean mIsAborted;

	private NotificationManager mNotificationManager;
	private Notification mNotification;
	private int mNotificationId;

	private MyBroadcastReceiver myBroadcastReceiver;

	private class MyBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			LogUtil.i("DownloadItem", "onReceive");
			if (intent != null) {
				LogUtil.i("DownloadItem", "onReceive111");
				onItemClick();
			}
		}
	}

	/**
	 * 
	 * @param context
	 * @param url
	 *            下载地址
	 */
	public DownloadItem(Context context, String url) {

		mContext = context;

		mUrl = url;
		mFileName = mUrl.substring(mUrl.lastIndexOf("/") + 1);

		checkFileName();

		mProgress = 0;

		mRunnable = null;
		mErrorMessage = null;

		mIsFinished = false;
		mIsAborted = false;

		Random r = new Random();
		mNotificationId = r.nextInt();
		mNotification = null;
		mNotificationManager = (NotificationManager) mContext
				.getSystemService(Context.NOTIFICATION_SERVICE);
		myBroadcastReceiver = new MyBroadcastReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.culiu.notification");
		mContext.registerReceiver(myBroadcastReceiver, filter);
	}

	/**
	 * 获取下载地址
	 * 
	 * @return
	 */
	public String getUrl() {
		return mUrl;
	}

	/**
	 * 获取文件名
	 * 
	 * @return
	 */
	public String getFileName() {
		return mFileName;
	}

	public void updateFileName(String fileName) {
		mFileName = fileName;
		checkFileName();
	}

	public String getFilePath() {
		return IOUtils.getDownloadFolder().getAbsolutePath() + File.separator
				+ mFileName;
	}

	/**
	 * 获取下载进度
	 * 
	 * @return
	 */
	public int getProgress() {
		return mProgress;
	}

	/**
	 * 设置当前任务错误信息
	 * 
	 * @param errorMessage
	 *            错误信息
	 */
	public void setErrorMessage(String errorMessage) {
		mErrorMessage = errorMessage;
	}

	/**
	 * 获取当前任务错误信息
	 * 
	 * @return 错误信息
	 */
	public String getErrorMessage() {
		return mErrorMessage;
	}

	/**
	 * 触发下载开始
	 */
	public void onStart() {
		createNotification();

		EventController.getInstance().fireDownloadEvent(
				EventConstants.EVT_DOWNLOAD_ON_START, this);
	}

	/**
	 * 设置任务为下载完成状态，触发一个下载完成事件
	 */
	public void onFinished() {
		mProgress = 100;
		mRunnable = null;

		mIsFinished = true;

		updateNotificationOnEnd();

		EventController.getInstance().fireDownloadEvent(
				EventConstants.EVT_DOWNLOAD_ON_FINISHED, this);
	}

	/**
	 * 设置当前进度，触发一个下载进度事件
	 * 
	 * @param progress
	 *            The current progress.
	 */
	public void onProgress(int progress) {
		mProgress = progress;
		EventController.getInstance().fireDownloadEvent(
				EventConstants.EVT_DOWNLOAD_ON_PROGRESS, this);
	}

	/**
	 * 开始下载
	 */
	public void startDownload() {
		if (mRunnable != null) {
			mRunnable.abort();
		}
		mRunnable = new DownloadRunnable(this);
		new Thread(mRunnable).start();
	}

	/**
	 * 中止当前下载
	 */
	public void abortDownload() {
		if (mRunnable != null) {
			mRunnable.abort();
		}
		mIsAborted = true;
	}

	/**
	 * 检查下载是否完成
	 * 
	 * @return True if the download is finished.
	 */
	public boolean isFinished() {
		return mIsFinished;
	}

	/**
	 * 检查下载是否中止
	 * 
	 * @return True if the download is aborted.
	 */
	public boolean isAborted() {
		return mIsAborted;
	}

	private void checkFileName() {
		int queryParamStart = mFileName.indexOf("?");
		if (queryParamStart > 0) {
			mFileName = mFileName.substring(0, queryParamStart);
		}
	}

	/**
	 * 创建一个下载notification
	 */
	private void createNotification() {
		mNotification = new Notification(
				R.drawable.download_anim,
				mContext.getString(R.string.DownloadNotification_DownloadStart),
				System.currentTimeMillis());

		Intent notificationIntent = new Intent(
				mContext.getApplicationContext(), DownloadsListActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(
                mContext.getApplicationContext(), 0, notificationIntent, 0);

		mNotification
				.setLatestEventInfo(
						mContext.getApplicationContext(),
						mContext.getString(R.string.DownloadNotification_DownloadInProgress),
						mFileName, contentIntent);

		mNotificationManager.notify(mNotificationId, mNotification);
	}

	/**
	 * 在下载完成时更新下载notification
	 */
	private void updateNotificationOnEnd() {
		if (mNotification != null) {
			mNotificationManager.cancel(mNotificationId);
		}

		String message;
		if (mIsAborted) {
			message = mContext
					.getString(R.string.DownloadNotification_DownloadCanceled);
		} else {
			message = mContext
					.getString(R.string.DownloadNotification_DownloadComplete);
		}

		mNotification = new Notification(
				R.drawable.stat_sys_download,
				mContext.getString(R.string.DownloadNotification_DownloadComplete),
				System.currentTimeMillis());
		mNotification.flags |= Notification.FLAG_AUTO_CANCEL;

		// Intent notificationIntent = new Intent(
		// mContext.getApplicationContext(), DownloadsListActivity.class);
		// PendingIntent contentIntent = PendingIntent.getActivity(
		// mContext.getApplicationContext(), 0, notificationIntent, 0);
		Intent notificationIntent = new Intent("com.culiu.notification");
		PendingIntent contentIntent = PendingIntent.getBroadcast(
                mContext.getApplicationContext(), 0, notificationIntent, 0);
		mNotification.setLatestEventInfo(mContext.getApplicationContext(),
				mFileName, message, contentIntent);

		mNotificationManager.notify(mNotificationId, mNotification);
	}

	/**
	 * 打开安装界面
	 */
	protected void onItemClick() {

		if (isFinished() && !isAborted() && getErrorMessage() == null) {

			File file = new File(getFilePath());
			if (file.exists()) {

				MimeTypeMap mime = MimeTypeMap.getSingleton();
				String ext = file.getName()
						.substring(file.getName().lastIndexOf(".") + 1)
						.toLowerCase();
				String type = mime.getMimeTypeFromExtension(ext);

				Intent i = new Intent(Intent.ACTION_VIEW);
				i.setDataAndType(Uri.fromFile(file), type);

				try {

					mContext.startActivity(i);

				} catch (ActivityNotFoundException e) {
					new AlertDialog.Builder(mContext)
							.setTitle(R.string.Main_VndErrorTitle)
							.setMessage(
									String.format(
                                            mContext.getString(R.string.Main_VndErrorMessage),
                                            getFilePath()))
							.setPositiveButton(android.R.string.ok,
									new AlertDialog.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
										}
									}).setCancelable(true).create().show();
				}
			}
		}
	}

}
